package com.lambkit.module.cms.web.admin.controller;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import com.jfinal.log.Log;
import com.jfinal.kit.StrKit;
import com.lambkit.component.swagger.annotation.Api;
import com.lambkit.component.swagger.annotation.ApiOperation;
import com.lambkit.core.aop.AopKit;
import com.lambkit.db.sql.column.Example;
import com.lambkit.module.admin.AdminManager;
import com.lambkit.module.upms.rpc.api.UpmsApiService;
import com.lambkit.module.upms.rpc.model.UpmsPermission;
import com.lambkit.module.upms.rpc.model.UpmsSystem;
import com.lambkit.module.upms.rpc.model.UpmsUser;
import com.lambkit.module.upms.rpc.model.sql.UpmsSystemCriteria;
import com.lambkit.module.upms.rpc.service.impl.UpmsApiServiceImpl;
import com.lambkit.web.controller.LambkitController;

/**
 * 后台controller
 */
//@RequestMapping("/manage")
@Api(tag = "后台控制器", description = "后台管理")
@RequiresAuthentication
public class ManageController extends LambkitController {

	private static final Log LOG = Log.getLog(ManageController.class);

	/**
	 * 后台首页
	 * @return
	 */
	@ApiOperation(tag = "后台首页")
	//@RequestMapping(value = "/index", method = RequestMethod.GET)
	public void index() {
		// 已注册系统
		Example upmsSystemExample = UpmsSystemCriteria.create()
				.andStatusEqualTo(1).example();
		List<UpmsSystem> upmsSystems = UpmsSystem.service().find(upmsSystemExample);
		setAttr("upmsSystems", upmsSystems);
		// 当前登录用户权限
		Subject subject = SecurityUtils.getSubject();
		String username = (String) subject.getPrincipal();
		System.out.println("auth:"+subject.isAuthenticated()+", name:"+username);
		if(StrKit.isBlank(username)) {
			// shiro退出登录
	        SecurityUtils.getSubject().logout();
			redirect("sso/login");
			return;
		}
		UpmsApiService upmsApiService = AopKit.get(UpmsApiServiceImpl.class);
		UpmsUser upmsUser = upmsApiService.selectUpmsUserByUsername(username);
		if(upmsUser==null) {
			// shiro退出登录
	        SecurityUtils.getSubject().logout();
			redirect("sso/login");
			return;
		}
		List<UpmsPermission> upmsPermissions = upmsApiService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
		setAttr("upmsPermissions", upmsPermissions);
		render(AdminManager.me().getTemplatePath() + "/cms/index.html");
	}

}